package com.dgut.app.config;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.dgut.common.config.WxAppConfig;
import com.dgut.common.mapper.WxUserMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.List;

/**
 * @author IT00ZYQ
 * @date 2021/5/9 18:15
 **/
@Configuration
@EnableScheduling
@Slf4j
public class TimeTask {
    private static final String TITLE = "每日日记与记账";
    private static final String CONTENT = "保持良好的习惯从记账和写日记开始哦";
    private static final String TEMPLATE_ID = "bJs74yC8wL9c7RbtVo9sPglIAhQbk41P7THmaUfEtJY";

    private final WxUserMapper wxUserMapper;
    public TimeTask(WxUserMapper wxUserMapper) {
        this.wxUserMapper = wxUserMapper;
    }

    @Scheduled(cron = "* * 21 * * ?")
    public void sendTip() {
        // 查询当天每天写日记或者记账的用户openid
        List<String> list = wxUserMapper.listNoFinishOpenId();
        for (String openid : list) {
            messageTemplate(openid);
        }
    }

    /**
     * 订阅消息
     * @param openid 微信用户openid
     */
    private void messageTemplate(String openid) {
        WxMaSubscribeMessage.Data thing1 = new WxMaSubscribeMessage.Data("thing1", TITLE);
        WxMaSubscribeMessage.Data thing2 = new WxMaSubscribeMessage.Data("thing2", CONTENT);
        List<WxMaSubscribeMessage.Data> list = new ArrayList<>();
        list.add(thing1);
        list.add(thing2);
        WxMaSubscribeMessage msg = WxMaSubscribeMessage.builder().toUser(openid).templateId(TEMPLATE_ID)
                .page("pages/index/index").data(list).build();
        WxMaMsgService msgService = WxAppConfig.wxMaService.getMsgService();
        try {
            msgService.sendSubscribeMsg(msg);
        } catch (WxErrorException e) {
            log.error("发送提醒每日日记与记账订阅消息失败，原因:{}",e.getMessage());
        }
    }

}
